﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using PagedList;
using System.Web.Security;

namespace MobileDesigner.Models
{
    public class SubordinatesController : Controller
    {
        private MobileDesignerContext db = new MobileDesignerContext();

        //
        // GET: /Subordinates/

        [Authorize(Roles = "Administrator, Partner's Manager, Partner, Manager, Regional Manager")]
        public ViewResult ListSubordinates(string sortOrder, string currentFilter, string searchString, int? page, int id = 0)
        {
            if (!IsUserSuperiorToSub(id))
                RedirectToAction("Index", "PrivateCabinet");
            id = (id != 0) ? id : WebSecurity.CurrentUserId;

            ViewBag.CurrentSort = sortOrder;
            ViewBag.EmailSortParm = String.IsNullOrEmpty(sortOrder) ? "Email desc" : "";
            ViewBag.NameSortParm = sortOrder == "Name" ? "Name desc" : "Name";

            if (Request.HttpMethod == "GET")
            {
                searchString = currentFilter;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter = searchString;

            var subordinates = from u in db.Users
                               where u.SuperiorID == id
                               select new SubordinatesListModel { ID = u.ID, Email = u.Email, Name = u.LastName + " " + u.Name, Phone = u.Phone };

            if (!String.IsNullOrEmpty(searchString))
            {
                subordinates = subordinates.Where(u => u.Email.ToUpper().Contains(searchString.ToUpper())
                                       || u.Name.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrder)
            {
                case "Name desc":
                    subordinates = subordinates.OrderByDescending(u => u.Name);
                    break;
                case "Email desc":
                    subordinates = subordinates.OrderByDescending(u => u.Email);
                    break;
                case "Name":
                    subordinates = subordinates.OrderBy(u => u.Name);
                    break;
                default:
                    subordinates = subordinates.OrderBy(u => u.Email);
                    break;
            }

            int pageSize = 3;
            int pageNumber = (page ?? 1);

            List<SubordinatesListModel> subordinatesList = new List<SubordinatesListModel>();
            foreach (var item in subordinates)
            {
                if (!Roles.IsUserInRole(item.Email, "Client"))
                    subordinatesList.Add(item);
            }

            return View(subordinatesList.ToPagedList(pageNumber, pageSize));
        }

        public ViewResult SubordinateClientList(int id, string sortOrderUser, string currentFilter, string searchString, int? page)
        {
            if (!IsUserSuperiorToSub(id))
                RedirectToAction("Index", "PrivateCabinet");
            ViewBag.CurrentSort = sortOrderUser;
            ViewBag.EmailSortParm = String.IsNullOrEmpty(sortOrderUser) ? "Email desc" : "";
            ViewBag.NameSortParm = sortOrderUser == "Name" ? "Name desc" : "Name";

            if (Request.HttpMethod == "GET")
            {
                searchString = currentFilter;
            }
            else
            {
                page = 1;
            }
            ViewBag.CurrentFilter = searchString;

            var clients = from u in db.Users
                          where u.SuperiorID == id
                          select new ClientListModel
                          {
                              ID = u.ID,
                              Email = u.Email,
                              Phone = u.Phone,
                              Name = u.LastName + " " + u.Name,
                          };

            if (!String.IsNullOrEmpty(searchString))
            {
                clients = clients.Where(u => u.Email.ToUpper().Contains(searchString.ToUpper())
                                       || u.Name.ToUpper().Contains(searchString.ToUpper()));
            }
            switch (sortOrderUser)
            {
                case "Name desc":
                    clients = clients.OrderByDescending(u => u.Name);
                    break;
                case "Email desc":
                    clients = clients.OrderByDescending(u => u.Email);
                    break;
                case "Name":
                    clients = clients.OrderBy(u => u.Name);
                    break;
                default:
                    clients = clients.OrderBy(u => u.Email);
                    break;
            }

            int pageSize = 3;
            int pageNumber = (page ?? 1);

            List<ClientListModel> clientList = new List<ClientListModel>();
            foreach (var item in clients)
            {
                if (Roles.IsUserInRole(item.Email, "Client"))
                    clientList.Add(item);
            }

            return View(clientList.ToPagedList(pageNumber, pageSize));
        }

        private bool IsUserSuperiorToSub(int id)
        {
            // id = 5, superioirID =? userId, userId.SuprioirID =? userID
            while (id != 0)
            {
                int superiorID = (from u in db.Users
                                  where u.ID == id
                                  select u.SuperiorID).FirstOrDefault();
                if (superiorID == WebSecurity.CurrentUserId)
                    return true;
                id = superiorID;
            }
            return false;
        }
    }
}
